import Config from '../utils/Config.js';

/**
 * 备战区组件
 * 负责左侧备战区域的显示和管理
 */
export default class BattleArea {
    constructor(uiManager) {
        this.uiManager = uiManager;
        this.layout = null;
        this.title = '备战区';
        
        // 动态卡牌
        this.dynamicCards = [];
        this.maxCards = 5;  // 初始容量5张，可通过提示功能扩展
        
        // 加载备战区卡片背景图片（支持数字和符号两种背景）
        this.cardImages = {
            number: null,  // icon_num.png - 数字卡牌背景
            symbol: null   // icon_fh.png - 符号卡牌背景
        };
        this.loadCardImages();
    }

    /**
     * 加载卡片背景图片（数字和符号两种）
     */
    loadCardImages() {
        // 加载数字卡牌背景（icon_num.png）
        this.cardImages.number = wx.createImage();
        this.cardImages.number.onload = () => {
            console.log('备战区数字卡牌背景图片加载完成');
        };
        this.cardImages.number.onerror = () => {
            console.log('备战区数字卡牌背景图片加载失败');
        };
        this.cardImages.number.src = 'images/icon_num.png';
        
        // 加载符号卡牌背景（icon_fh.png）
        this.cardImages.symbol = wx.createImage();
        this.cardImages.symbol.onload = () => {
            console.log('备战区符号卡牌背景图片加载完成');
        };
        this.cardImages.symbol.onerror = () => {
            console.log('备战区符号卡牌背景图片加载失败');
        };
        this.cardImages.symbol.src = 'images/icon_fh.png';
    }

    /**
     * 设置布局
     */
    setLayout(layout) {
        // 添加刘海屏安全边距，避免卡片被刘海遮挡
        const notchSafeMargin = 40; // 刘海屏安全边距（左边距）
        
        this.layout = {
            x: layout.x + notchSafeMargin,
            y: layout.y,
            width: layout.width - notchSafeMargin,
            height: layout.height
        };
        
        console.log('备战区布局设置（已添加刘海屏安全边距）:', this.layout);
        console.log(`备战区可点击区域: x=[${this.layout.x}, ${this.layout.x + this.layout.width}], y=[${this.layout.y}, ${this.layout.y + this.layout.height}]`);
    }

    /**
     * 渲染组件
     */
    render(ctx) {
        if (!this.layout) return;

        const { x, y, width, height } = this.layout;
        
        // 绘制标题（减小高度从40px到30px）
        this.drawTitle(ctx, x, y, width, 30);
        
        // 绘制内容区域（背景）
        this.drawContentArea(ctx, x, y + 30, width, height - 30);
        
        // 绘制卡牌
        this.drawLeftSideCards(ctx, x, y + 30, width, height - 30);
    }

    /**
     * 绘制标题
     */
    drawTitle(ctx, x, y, width, height) {
        // 绘制绿色背景
        ctx.fillStyle = Config.COLORS.PRIMARY; // 绿色背景
        ctx.fillRect(x, y, width, height);
        
        // 标题文字（白色）
        ctx.fillStyle = '#FFFFFF';
        ctx.font = 'bold 14px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(this.title, x + width/2, y + height/2 + 5);
    }

    /**
     * 绘制内容区域
     */
    drawContentArea(ctx, x, y, width, height) {
        // 备战区域不绘制背景，与游戏主背景无缝融合
        // 移除所有背景、边框和占位文字，实现视觉"无感"效果
    }

    /**
     * 检查点是否在组件内
     */
    isPointInside(x, y) {
        if (!this.layout) {
            return false;
        }
        
        return x >= this.layout.x && 
               x <= this.layout.x + this.layout.width &&
               y >= this.layout.y && 
               y <= this.layout.y + this.layout.height;
    }

    /**
     * 处理触摸开始事件
     */
    onTouchStart(x, y) {
        console.log(`BattleArea.onTouchStart: 接收到点击(${x}, ${y})`);

        // 显示所有卡牌的调试边框，帮助可视化
        this.dynamicCards.forEach(card => {
            card.showDebugBorder = true;
        });
        setTimeout(() => {
            this.dynamicCards.forEach(card => {
                card.showDebugBorder = false;
            });
        }, 2000);

        // 命中检测：如果点到卡牌，则交给 GameBoard 处理移回底部
        const clicked = this.checkCardClick(x, y);
        if (clicked) {
            console.log(`BattleArea: 点击命中卡牌 ${clicked.value}，准备移回底部`);
            const gameBoard = this.uiManager && this.uiManager.components && this.uiManager.components.gameBoard;
            if (gameBoard && typeof gameBoard.handleSidePanelCardClick === 'function') {
                // 直接传递卡牌对象，避免二次检测
                gameBoard.handleSidePanelCardClick(clicked);
                return true;
            }
        }
        console.log('BattleArea: 未命中卡牌');
        return false;
    }

    /**
     * 点击检测:直接使用卡牌存储的坐标信息
     * 优化：只检测卡牌的可见区域（露出部分）
     */
    checkCardClick(x, y) {
        if (!this.layout || !this.dynamicCards || this.dynamicCards.length === 0) return null;

        console.log(`备战区点击检测: 点击坐标(${x}, ${y}), 卡牌数量=${this.dynamicCards.length}`);

        // 卡牌重叠参数（与drawLeftSideCards保持一致）
        const overlapPercent = 0.65;
        
        // 从上到下反向遍历，优先检测最上层的卡牌
        for (let i = this.dynamicCards.length - 1; i >= 0; i--) {
            const card = this.dynamicCards[i];

            // 使用渲染时保存的坐标
            if (card.x !== undefined && card.y !== undefined && card.width !== undefined && card.height !== undefined) {
                const cardX = card.x;
                const cardY = card.y;
                const cardWidth = card.width;
                const cardHeight = card.height;
                
                // 计算可见高度
                const visibleHeight = cardHeight * (1 - overlapPercent);
                
                // 判断是否为最后一张卡牌（最上层）
                const isLastCard = (i === this.dynamicCards.length - 1);
                
                // 最后一张卡牌可点击完整区域，其他卡牌只能点击露出的顶部区域
                const clickableHeight = isLastCard ? cardHeight : visibleHeight;
                
                // X轴检测：完整宽度
                const xInRange = x >= cardX && x <= cardX + cardWidth;
                
                // Y轴检测：只检测可见部分
                const yInRange = y >= cardY && y <= cardY + clickableHeight;

                // 添加调试日志
                console.log(`  检查卡牌${i}(${isLastCard ? '最上层' : '中间层'}): 完整区域[${cardX}, ${cardX + cardWidth}] x [${cardY}, ${cardY + cardHeight}]`);
                console.log(`  可点击区域: [${cardX}, ${cardX + cardWidth}] x [${cardY}, ${cardY + clickableHeight}] (高度=${clickableHeight.toFixed(1)}px)`);
                console.log(`  点击检测: x(${x}) in range? ${xInRange}, y(${y}) in range? ${yInRange}`);

                if (xInRange && yInRange) {
                    console.log(`  ✓ 命中卡牌${i}: ${card.value} (点击了${isLastCard ? '完整区域' : '露出部分'})`);
                    // 临时启用调试边框
                    card.showDebugBorder = true;
                    // 1秒后关闭调试边框
                    setTimeout(() => {
                        card.showDebugBorder = false;
                    }, 1000);
                    return card;
                }
            }
        }
        console.log('  ✗ 未命中任何卡牌');
        return null;
    }

    /**
     * 绘制左侧备战区卡片
     */
    drawLeftSideCards(ctx, x, y, width, height) {
        if (!this.dynamicCards || this.dynamicCards.length === 0) return;

        const cardWidth = 60;
        const cardHeight = 106;
        const overlapPercent = 0.65;
        const visibleHeight = cardHeight * (1 - overlapPercent);
        const topPadding = 5;
        // 卡牌在备战区内居中显示
        const centerOffsetX = Math.floor(width - cardWidth) / 2;

        // 只在第一次绘制或卡牌数量变化时输出调试信息
        if (!this._lastCardCount || this._lastCardCount !== this.dynamicCards.length) {
            console.log(`[绘制卡牌] 传入参数: x=${x}, y=${y}, width=${width}, height=${height}`);
            console.log(`[绘制卡牌] centerOffsetX=${centerOffsetX}, 卡牌数量=${this.dynamicCards.length}`);
            this._lastCardCount = this.dynamicCards.length;
        }

        for (let i = 0; i < this.dynamicCards.length; i++) {
            const card = this.dynamicCards[i];
            // 使用传入的参数 x, y 而不是 this.layout
            const cardX = x + centerOffsetX;
            const cardY = y + topPadding + i * visibleHeight;

            // 更新点击区域
            card.x = cardX;
            card.y = cardY;
            card.width = cardWidth;
            card.height = cardHeight;

            // 只在坐标发生变化时输出调试信息
            if (!card._lastX || card._lastX !== cardX || card._lastY !== cardY) {
                console.log(`[绘制卡牌${i}] 位置更新: (${cardX}, ${cardY}) 尺寸: ${cardWidth}x${cardHeight}`);
                card._lastX = cardX;
                card._lastY = cardY;
            }

            this.drawBattleCard(ctx, card, cardX, cardY, cardWidth, cardHeight);
        }
    }

    drawBattleCard(ctx, card, x, y, width, height) {
        // 只在第一次绘制时输出调试信息
        if (!card._drawLogged) {
             card._drawLogged = true;
        }

        // 始终绘制一个可见的背景，确保点击区域可见
        // 先绘制背景矩形
        ctx.fillStyle = card.selected ? '#4CAF50' : '#E0E0E0';
        ctx.fillRect(x, y, width, height);
        ctx.strokeStyle = card.selected ? '#4CAF50' : '#CCCCCC';
        ctx.lineWidth = card.selected ? 3 : 1;
        ctx.strokeRect(x, y, width, height);

        // 根据卡牌类型选择背景图片
        const isNumberCard = typeof card.value === 'number';
        const cardImage = isNumberCard ? this.cardImages.number : this.cardImages.symbol;
        
        // 如果图片加载完成，在背景上绘制图片
        if (cardImage && cardImage.complete) {
            // 图片稍微缩小一点，留出边框
            const imageMargin = 2;
            const imageX = x + imageMargin;
            const imageY = y + imageMargin;
            const imageWidth = width - imageMargin * 2;
            const imageHeight = height - imageMargin * 2;

            ctx.drawImage(cardImage, imageX, imageY, imageWidth, imageHeight);

            // 只在第一次绘制时记录图片坐标
            if (!card._imageLogged) {
                 card._imageLogged = true;
            }
        }

        // 绘制图案
        if (card.patternImage && card.patternImage.complete) {
            const patternSize = 35;
            const patternX = x + (width - patternSize) / 2;
            const patternY = y + (height - patternSize) / 2;
            ctx.drawImage(card.patternImage, patternX, patternY, patternSize, patternSize);
        }

        // 绘制数字
        ctx.fillStyle = '#333333';
        ctx.font = 'bold 14px Arial';
        ctx.strokeStyle = '#FFFFFF';
        ctx.lineWidth = 2;

        ctx.textAlign = 'left';
        ctx.strokeText(String(card.value), x + 5, y + 16);
        ctx.fillText(String(card.value), x + 5, y + 16);

        ctx.textAlign = 'right';
        ctx.strokeText(String(card.value), x + width - 5, y + height - 8);
        ctx.fillText(String(card.value), x + width - 5, y + height - 8);

        // 添加调试边框，帮助可视化点击区域
        if (card.showDebugBorder) {
            ctx.strokeStyle = '#FF0000';
            ctx.lineWidth = 2;
            ctx.setLineDash([5, 5]);
            ctx.strokeRect(x, y, width, height);
            ctx.setLineDash([]);
        }
    }

    /** 动态卡牌 API，与旧 SidePanel 保持兼容 **/
    addCardToBattleArea(bottomCard) {
        if (!bottomCard) return false;
        if (this.dynamicCards.length >= this.maxCards) {
            console.log('备战区已满，无法添加更多卡牌');
            return false;
        }
        const battleCard = {
            id: `battle_${Date.now()}_${Math.random()}`,
            type: bottomCard.type,
            value: bottomCard.value,
            patternIndex: bottomCard.patternIndex,
            patternImage: bottomCard.patternImage,
            originalBottomCard: bottomCard,
            area: 'battle',
            visible: true,
            selected: false
        };
        this.dynamicCards.push(battleCard);
        console.log(`卡牌 ${bottomCard.value} 已添加到备战区`);
        return true;
    }

    removeCardFromBattleArea(battleCard) {
        const index = this.dynamicCards.indexOf(battleCard);
        if (index !== -1) {
            this.dynamicCards.splice(index, 1);
            console.log(`卡牌 ${battleCard.value} 已从备战区移除`);
            return battleCard.originalBottomCard;
        }
        return null;
    }

    getDynamicCards() {
        return this.dynamicCards;
    }

    /**
     * 扩展备战区容量（每次+1）
     * @returns {number} 扩展后的最大容量
     */
    increaseCapacity() {
        this.maxCards++;
        console.log(`[BattleArea] 容量已扩展，当前最大容量: ${this.maxCards}`);
        return this.maxCards;
    }

    /**
     * 调试方法：显示所有卡牌的边框
     */
    showAllCardBorders(duration = 3000) {
        console.log(`[BattleArea] 显示所有卡牌调试边框，持续${duration}ms`);
        this.dynamicCards.forEach((card, index) => {
            card.showDebugBorder = true;
        });

        setTimeout(() => {
            this.dynamicCards.forEach(card => {
                card.showDebugBorder = false;
            });
            console.log(`[BattleArea] 调试边框已隐藏`);
        }, duration);
    }

    /**
     * 调试方法：输出当前所有卡牌的详细信息
     */
    debugCardPositions() {
        console.log(`[BattleArea] === 卡牌位置调试信息 ===`);
        console.log(`[BattleArea] 备战区布局: x=${this.layout?.x}, y=${this.layout?.y}, w=${this.layout?.width}, h=${this.layout?.height}`);
        console.log(`[BattleArea] 卡牌数量: ${this.dynamicCards.length}`);

        this.dynamicCards.forEach((card, index) => {
            console.log(`[BattleArea] 卡牌${index}: 值=${card.value}`);
            console.log(`[BattleArea]   - 位置: (${card.x}, ${card.y})`);
            console.log(`[BattleArea]   - 尺寸: ${card.width}x${card.height}`);
            console.log(`[BattleArea]   - 区域: [${card.x}, ${card.x + card.width}] x [${card.y}, ${card.y + card.height}]`);
        });
        console.log(`[BattleArea] === 调试信息结束 ===`);
    }
}
